package com.ruyuan.eshop.data.migrate.tool.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.otter.canal.protocol.CanalEntry;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruyuan.eshop.data.migrate.tool.mapper.targetdb.TargetOrderInfoMapper;
import com.ruyuan.eshop.data.migrate.tool.model.order.OrderInfoDO;
import com.ruyuan.eshop.data.migrate.tool.service.TargetOrderInfoService;
import com.ruyuan.eshop.data.migrate.tool.util.LoggerFormat;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author zhonghuashishan
 * @version 1.0
 */
@Slf4j
@Service
public class TargetOrderInfoServiceImpl implements TargetOrderInfoService {

    @Autowired
    private TargetOrderInfoMapper targetOrderInfoMapper;

    @Override
    public Long getMaxId() {
        return targetOrderInfoMapper.getMaxId();
    }

    @Override
    @Transactional(transactionManager = "TargetTransactionManager")
    public void consumer(CanalEntry.EventType eventType, JSONObject beforeData, JSONObject afterData) {

        log.info(LoggerFormat.build()
                .remark("consumer->request")
                .data("eventType", eventType)
                .data("beforeData", beforeData)
                .data("afterData", afterData)
                .finish());

        if(CanalEntry.EventType.INSERT.equals(eventType) || CanalEntry.EventType.UPDATE.equals(eventType)) {
            OrderInfoDO orderInfoDO = afterData.toJavaObject(OrderInfoDO.class);

            // 新增或更新记录
            insertOrUpdate(orderInfoDO.getId(), orderInfoDO);
            return;
        }

        if(CanalEntry.EventType.DELETE.equals(eventType)) {
            OrderInfoDO orderInfoDO = beforeData.toJavaObject(OrderInfoDO.class);

            // 删除记录
            delete(orderInfoDO.getId(), orderInfoDO.getOrderId());
        }
    }

    @Override
    @Transactional(transactionManager = "TargetTransactionManager")
    public void batchInsert(List<OrderInfoDO> orderInfoDOList) {

        log.info(LoggerFormat.build()
                .remark("sync->request")
                .data("orderInfoDOList", orderInfoDOList)
                .finish());

        targetOrderInfoMapper.batchInsert(orderInfoDOList);
    }

    /**
     * 新增操作 或者 更新操作
     * @param orderInfoDO 订单信息
     */
    private void insertOrUpdate(Long id, OrderInfoDO orderInfoDO) {
        String orderId = orderInfoDO.getOrderId();
        // 先验证一下是否存在历史数据
        Date gmtModified = targetOrderInfoMapper.getGmtModified(id, orderId);
        if(gmtModified == null) {
            // 不存在则执行新增操作
            targetOrderInfoMapper.insert(orderInfoDO);
            return;
        }

        // 已经存在记录了，比较一下gmtModified
        if(orderInfoDO.getGmtModified().after(gmtModified)) {
            // 如果当前的记录比较新，则执行更新操作
            LambdaUpdateWrapper<OrderInfoDO> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(OrderInfoDO::getId, id);
            updateWrapper.eq(OrderInfoDO::getOrderId, orderId);
            targetOrderInfoMapper.update(orderInfoDO, updateWrapper);
        }

        // 否则，丢弃记录不处理

    }

    /**
     * 删除操作
     * @param orderId 订单ID
     */
    private void delete(Long id, String orderId) {
        LambdaQueryWrapper<OrderInfoDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderInfoDO::getId, id);
        queryWrapper.eq(OrderInfoDO::getOrderId, orderId);
        targetOrderInfoMapper.delete(queryWrapper);
    }

}